Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Networking → ServerSocket Class

Networking

ServerSocket Class

The `ServerSocket` class in Java is a crucial component for building network servers. It allows a server application to listen for incoming connections from clients on a specified port. Once a connection request arrives, the `ServerSocket` accepts it, creating a new `Socket` object that facilitates communication with the client. Let's break down its functionality and usage with detailed explanations and examples.

ServerSocket Methods and Functionality:

1. `ServerSocket(int port)`: This constructor creates a `ServerSocket` that listens for connections on the specified `port`. `port` must be a valid port number (typically between 1024 and 65535). If the port is already in use, a `BindException` is thrown. ⮚ 2. `ServerSocket(int port, int backlog)`: This constructor adds a `backlog` parameter. `backlog` specifies the maximum number of pending connections that can be queued before the server is unable to accept new connections. A higher backlog allows more clients to wait while the server processes existing connections, but consumes more system resources. ⮚ 3. `ServerSocket(int port, int backlog, InetAddress bindAddr)`: This constructor allows specifying the `InetAddress` (IP address) to bind the server to. This is useful for servers that need to listen on a specific network interface rather than all available interfaces. ⮚ 4. `accept()`: This is the core method of `ServerSocket`. It blocks (waits) until a client attempts to connect. Upon a successful connection, it returns a new `Socket` object representing the connection to that client. This `Socket` can then be used for input/output operations (sending and receiving data). ⮚ 5. `close()`: This method closes the `ServerSocket`, preventing further connections. It's crucial to close the `ServerSocket` when it's no longer needed to release resources. ⮚ 6. `isClosed()`: Checks if the `ServerSocket` is closed. ⮚ 7. `getLocalPort()`: Returns the port number the server is listening on. This can be useful for debugging or dynamic port allocation scenarios. ⮚ 8. `getLocalSocketAddress()`: Returns the `SocketAddress` of the server.

A Simple Echo Server

This example demonstrates a basic echo server that receives messages from clients and sends them back:
Simple ServerSocket example import java.io.*; import java.net.*; public class EchoServer { public static void main(String[] args) { int port = 8080; // Choose a port number try (ServerSocket serverSocket = new ServerSocket(port)) { System.out.println("Echo server started on port " + port); while (true) { Socket clientSocket = serverSocket.accept(); // Blocks until a client connects System.out.println("Client connected: " + clientSocket.getInetAddress()); new Thread(() -> handleClient(clientSocket)).start(); // Handle each client in a separate thread } } catch (IOException e) { System.err.println("Error starting or running server: " + e.getMessage()); } } private static void handleClient(Socket clientSocket) { try ( BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true) ) { String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println("Received: " + inputLine); out.println("Echo: " + inputLine); // Echo back the message if (inputLine.equals("bye")) break; // Simple termination condition } } catch (IOException e) { System.err.println("Error handling client: " + e.getMessage()); } finally { try { clientSocket.close(); } catch (IOException e) { System.err.println("Error closing client socket: " + e.getMessage()); } } } }
Explanation: ⮚ The server creates a `ServerSocket` on port 8080. ⮚ The `accept()` method blocks until a client connects. ⮚ Each client connection is handled in a separate thread using `new Thread(...)` to prevent blocking. This is crucial for handling multiple clients concurrently. ⮚ `BufferedReader` and `PrintWriter` are used for efficient reading and writing of text data. ⮚ The server echoes back whatever the client sends. ⮚ `try-with-resources` ensures that sockets and streams are closed properly, even if exceptions occur. Important Considerations: Error Handling: Robust error handling (using `try-catch` blocks) is essential to deal with potential exceptions like `IOException`, `BindException`, etc. Multithreading: For handling multiple clients simultaneously, multithreading (as shown in the example) is necessary. Consider using a thread pool for better resource management in high-concurrency scenarios. Security: Production servers require careful security considerations, including input validation, authentication, and authorization mechanisms.

Tutorials